//
// 配合php项目经常会用到的方法
//

/**
 * 当前时间戳
 * @return {Int} PHP当前时间戳
 */
export const now = () => {
  return Number(Math.floor(new Date().getTime() / 1000));
}


/**
 * 字符串转时间戳
 * @param  {String} str 时间日期字符串
 * @return {Int}     PHP对应时间戳
 */
export const str2time = str => {
  let new_str = str.replace(/:/g,'-'), arr, datum;
  new_str = new_str.replace(/ /g,'-');
  arr = new_str.split('-');
  if(arr.length < 6){
    arr[3] = arr[4] = arr[5] = '00';
  }
  datum = new Date(Date.UTC(arr[0],arr[1]-1,arr[2],arr[3]-8,arr[4],arr[5]));
  return datum.getTime() / 1000;
}


/**
 * 时间戳转字符串
 * @param  {Int} ts    php时间戳
 * @param  {Object} options 设置对象
 * @return {String}
 */
export const time2str = (ts, opts={}) => {
  let
    dt = new Date(ts * 1000),
    y = dt.getFullYear(),
    m = dt.getMonth() + 1,
    d = dt.getDate(),
    h = dt.getHours(),
    min = dt.getMinutes(),
    sec = dt.getSeconds(),
    sp = opts.sp || '-';
  m = m < 10 ? `0${m}` : m;
  d = d < 10 ? `0${d}` : d;
  h = h < 10 ? `0${h}` : h;
  min = min < 10 ? `0${min}` : min;
  sec = sec < 10 ? `0${sec}` : sec;
  if(opts.style == 1){
    return `${y}${sp}${m}${sp}${d} ${h}:${min}:${sec}`;
  }
  if(opts.style == 2){
    return `${m}${sp}${d} ${h}:${min}`;
  }
  return y+sp+m+sp+d;
}
